package com.jtpay.ysfproductionprocess.http.JsonConver;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.jtpay.ysfproductionprocess.utils.LogUtil;
import com.jtpay.ysfproductionprocess.utils.PayDESUtil;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import java.io.IOException;
import java.io.StringReader;

/**
 * Description:
 * File: JsonResponseBodyConverter.java
 * Author: Administrator
 * Create: 2018/08/16 15:49
 */
public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    /**
     * 构造器
     */
    JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    /**
     * 转换
     *
     * @param responseBody ResponseBody
     * @return T
     * @throws IOException IOException
     */
    @Override
    public T convert(ResponseBody responseBody) throws IOException {

        String response = responseBody.string();
        LogUtil.log("待解密的服务器数据：" + response);
        String result = PayDESUtil.decode(response);//解密

        LogUtil.log("解密的服务器数据：" + result);
        JsonReader jsonReader = gson.newJsonReader(new StringReader(result));
        try {
            return adapter.read(jsonReader);
        } finally {
            responseBody.close();
        }


    }
}
